import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseInterceptors,
  UploadedFile,
  BadRequestException,
  UploadedFiles,
} from '@nestjs/common';
import { Express } from 'express';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { MulterError } from 'multer';
import { ConfigService } from '@nestjs/config';
import { UploadService } from './upload.service';
// import { CreateUploadDto } from './dto/create-upload.dto';
import { UpdateUploadDto } from './dto/update-upload.dto';
import { Public } from 'src/utils/skip.jwt';

@Controller('grocery/upload')
export class UploadController {
  constructor(
    private readonly uploadService: UploadService,
    private configService: ConfigService,
  ) {}

  @Post('file')
  @UseInterceptors(FileInterceptor('file'))
  create(@Body() body, @UploadedFile() file: Express.Multer.File) {
    const dest = file.path.split('static/')[1]
    try {
      if (file) {
        return {
          name: file.filename,
          url: `${this.configService.get('SERVICE_BASE_URL')}/${dest}`,
        };
      }
    } catch(e) {
      // throw new MulterError('LIMIT_UNEXPECTED_FILE');
      throw new BadRequestException({code: 'LIMIT_UNEXPECTED_FILE', message: '文件不能为空'});
    }
  }

  // todo 同时上传多个文件
  // @Post('filelist')
  // @UseInterceptors(FilesInterceptor('file'))
  // createFileList(@Body() body, @UploadedFiles() file) {
  //   console.log('body: ', body)
  //   console.log('file123: ', file)
  //   if (file) {
  //     return '上传成功';
  //   }
  //   throw new MulterError('LIMIT_UNEXPECTED_FILE')
  //   // throw new BadRequestException({code: 'LIMIT_UNEXPECTED_FILE', message: '文件不能为空'});
  // }

  // @Public()
  @Get('info')
  async getTest() {
    return 'upload'
  }
}
